package org.films.domain;

import java.util.Calendar;
import java.util.Date;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.films.domain.Actor;
import org.films.domain.Study;

privileged aspect Film_Roo_Finder {
    
    public static Query Film.findFilmsByStudyAndReleaseYearEquals(Study study, Date releaseYear) {    
        if (study == null) throw new IllegalArgumentException("The study argument is required");        
        if (releaseYear == null) throw new IllegalArgumentException("The releaseYear argument is required");        
        EntityManager em = Film.entityManager();        
        Query q = em.createNativeQuery("select *  from film f where" +
        		" f.study = ? and date_part('year', f.release_year) = ?", Film.class);        
        q.setParameter(1, study.getId()); 
        Calendar cal = Calendar.getInstance();
    	cal.setTime(releaseYear);    	
        q.setParameter(2, cal.get(Calendar.YEAR));          
        return q;        
    }    
    
    public static Query Film.findFilmsByActors(Set<Actor> actors) {    
        if (actors == null) throw new IllegalArgumentException("The actors argument is required");        
        EntityManager em = Film.entityManager();        
        StringBuilder queryBuilder = new StringBuilder("SELECT Film FROM Film AS film WHERE");        
        for (int i = 0; i < actors.size(); i++) {        
            if (i > 0) queryBuilder.append(" AND");            
            queryBuilder.append(" :actors_item").append(i).append(" MEMBER OF film.actors");            
        }        
        Query q = em.createQuery(queryBuilder.toString());        
        int actorsIndex = 0;        
        for (Actor _actor: actors) {        
            q.setParameter("actors_item" + actorsIndex++, _actor);            
        }        
        return q;        
    }    
    
}
